function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        try { resolve(JSON.parse(xhr.responseText)); } catch (e) { reject(new Error('Invalid JSON')); }
      } else { reject(new Error('HTTP ' + xhr.status)); }
    };
    xhr.onerror = () => reject(new Error('Network error'));
    xhr.send();
  });
}

function formatNumber(num) {
  if (num >= 1000000) return (num/1000000).toFixed(1) + 'M';
  if (num >= 1000) return (num/1000).toFixed(1) + 'K';
  return (num||0).toString();
}

async function renderAllPlayers() {
  const grid = document.getElementById('playersGrid');
  try {
    const resp = await fetchData('http://localhost:8989/api/data');
    const userMap = resp.user || {};
    const players = Object.keys(userMap).map(uid => ({ uid, ...userMap[uid] }));
    // 默认按总伤害排序
    players.sort((a,b)=> (b.total_damage?.total||0) - (a.total_damage?.total||0));
    const max = players.length>0 ? (players[0].total_damage?.total||1) : 1;
    let html = '';
    players.forEach(p => {
      const dmg = p.total_damage?.total || 0;
      const heal = p.total_healing?.total || 0;
      const taken = p.taken_damage || 0;
      const percent = Math.round((dmg/max)*100);
      html += `
        <div class="card">
          <div class="header">
            <div class="name">${p.nickname || p.name || ('玩家_'+p.uid)}</div>
            <div class="profession">${p.profession || '未知'}</div>
          </div>
          <div class="bar"><div class="fill" style="width:${percent}%"></div></div>
          <div class="stats">
            <div class="stat"><span class="label">总伤害</span><span class="value">${formatNumber(dmg)}</span></div>
            <div class="stat"><span class="label">总治疗</span><span class="value">${formatNumber(heal)}</span></div>
            <div class="stat"><span class="label">总承伤</span><span class="value">${formatNumber(taken)}</span></div>
          </div>
        </div>`;
    });
    grid.innerHTML = html || '<div class="loading">📭 暂无数据</div>';
  } catch (e) {
    grid.innerHTML = '<div class="loading">❌ 加载失败</div>';
  }
}

document.addEventListener('DOMContentLoaded', renderAllPlayers);

